package com.xj.pattern.proxy.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

import com.xj.pattern.proxy.annotation.Transactional;
import com.xj.pattern.proxy.transactional.TransactionalManager;

public class JDKProxy implements InvocationHandler {

	private TransactionalManager transactionalManager = new TransactionalManager();
	
	private Object targetClass;
	
	public JDKProxy(Object targetClass) {
		this.targetClass = targetClass;
	}
	public Object createProxy(){
		
		return Proxy.newProxyInstance(this.getClass().getClassLoader(), targetClass.getClass().getInterfaces(), this);
	}
	
	@Override
	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
		Object obj = null;
		//判断方法上是否包含transactional注解，如果有则执行事务，否则不执行
		if(method.isAnnotationPresent(Transactional.class) || method.getDeclaringClass().isAnnotationPresent(Transactional.class)
				||targetClass.getClass().isAnnotationPresent(Transactional.class) 
				|| targetClass.getClass().getMethod(method.getName(), method.getParameterTypes()).isAnnotationPresent(Transactional.class)){
			try {
					transactionalManager.begin();
					
					obj = method.invoke(targetClass, args);
					
					transactionalManager.commit();
				
			} catch (Exception e) {
				transactionalManager.rollback();
			}
		}else{
			obj = method.invoke(targetClass, args);
		}
		
		return obj;
	}

}
